<template>
  <div class="hedge-strategy layout-content">
    <div class="hedgeCategory">
      <a-card title="套保品种及比例">
        <c-form
          v-model="form"
          :data="formData"
          ref="form"
          :col="{
            labelCol: { style: 'width: 110px' },
            wrapperCol: { style: 'width: 250px' }
          }"
        >
          <template v-slot:categoryId>
            <c-category
              v-model="form.categoryId"
              :filterList="filterCategorys"
            ></c-category>
          </template>
          <template v-slot:scale>
            100%
          </template>
          <template v-slot:createDate>
            {{ $getTime(updateData.createDate) }}
          </template>
          <template v-slot:updateDate>
            {{ $getTime(updateData.updateDate) }}
          </template>
        </c-form>
      </a-card>
    </div>
    <div class="hedgeWarehouse">
      <a-card title="开仓/平仓策略">
        <div class="content info">
          <p>
            <c-desc :column="1" :columns="warehouseColumns">
              <template v-slot:openingRule>
                <a-radio-group v-model="openingRule">
                  <a-radio :value="1">
                    保值
                  </a-radio>
                  <a-radio :value="2">
                    投机
                  </a-radio>
                </a-radio-group>
              </template>
              <template v-slot:closingRule>
                <a-radio-group v-model="closingRule">
                  <a-radio :value="1">
                    昨仓
                  </a-radio>
                  <a-radio :value="2">
                    今仓
                  </a-radio>
                </a-radio-group>
              </template>
            </c-desc>
          </p>
          <p>
            <a-alert type="warning">
              <template slot="message">
                <p>
                  1、平仓时，优先平投机仓，然后是套利仓，最后才是保值仓
                </p>
                <span>
                  2、根据期货市场的交易规则，在换月的前三个交易日 开仓只能开投机
                  不能开保值
                </span>
              </template>
            </a-alert>
          </p>
        </div>
      </a-card>
    </div>
    <div class="hedgeDelivery">
      <a-card title="交割月策略">
        <div class="content">
          <p>
            <a-alert type="warning">
              <template slot="message">
                <p>
                  合约进入交割月后，期货交易所对某些品种的持仓会有指定整数倍要求，如铜、铝、锌进入交割月时，其持仓手数必须满足5手的整数倍；若小于最小整数倍要求时，则直接挂在次月，挂在次月的价格=客户下单价+（次月最新价-当月最新价）。
                </p>
                <span>
                  对此，实现自动套保时，当交易对手点价不是指定的整数倍（出现超过整数倍的情况），选择以下方式：
                </span>
              </template>
            </a-alert>
          </p>
          <a-radio-group v-model="deliveryRule" buttonStyle="solid">
            <template v-for="item in hedgeDict.deliveryRule">
              <a-radio :value="item.value" :key="item.value">
                <a-tag color="orange">策略{{ item.value }}</a-tag>
                <span>{{ item.desc }}</span>
              </a-radio>
            </template>
          </a-radio-group>
        </div>
      </a-card>
    </div>
    <div class="submit">
      <c-button type="primary" @click="submit">确认提交</c-button>
    </div>
  </div>
</template>

<script>
import {
  gethedgeaccountlist,
  addcompanyhedgeconfig,
  updatecompanyhedgeconfig,
  querycompanyhedgeconfig
} from "@/api/hedge";
import { mapState } from "vuex";
import hedgeDict from "@/dict/hedge";

const warehouseColumns = [
  {
    label: "开仓时，开仓类型优先选择",
    slot: "openingRule"
  },
  {
    label: "平仓时，平仓优先选择",
    slot: "closingRule"
  }
];

export default {
  data() {
    return {
      hedgeDict,
      updateData: {}, // 编辑时的数据，用于回写
      form: {
        categoryId: undefined,
        hedgeAccountId: undefined
      },
      filterCategorys: [], // 过滤的品种
      accountList: [],
      warehouseColumns,
      openingRule: 2,
      closingRule: 1,
      deliveryRule: 1
    };
  },
  computed: {
    ...mapState(["resource"]),
    // 是否编辑状态
    isUpdate() {
      return this.$route.name === "hedgeStrategyUpdate";
    },
    formData() {
      let res = [
        {
          label: "套保品种",
          prop: "categoryId",
          slot: "categoryId",
          required: true
        },
        {
          label: "套保比例",
          prop: "scale",
          slot: "scale"
        },
        {
          label: "套保账户",
          prop: "hedgeAccountId",
          placeholder: "请选择套保账户",
          type: "select",
          typeData: this.accountList,
          replaceFields: {
            value: "id",
            label: "futuresCompanyName"
          },
          selectOptionLabel: item => {
            return item.futuresCompanyName + " " + item.accountId;
          },
          required: true
        },
        {
          label: "创建时间",
          prop: "createDate",
          slot: "createDate",
          hidden: this.isUpdate ? false : true
        },
        {
          label: "最后更新时间",
          prop: "updateDate",
          slot: "updateDate",
          hidden: this.isUpdate ? false : true
        }
      ];
      return res;
    }
  },
  methods: {
    // 提交
    submit() {
      let _this = this;
      _this.$refs.form.validated().then(() => {
        this.$confirm({
          title: "温馨提示",
          content: "新增或编辑后，需等待期货休盘后才生效",
          onOk() {
            return new Promise((resolve, reject) => {
              let request = _this.isUpdate
                ? updatecompanyhedgeconfig
                : addcompanyhedgeconfig;
              request({
                id: _this.isUpdate ? _this.updateData.id : undefined,
                categoryId:
                  _this.form.categoryId[_this.form.categoryId.length - 1],
                hedgeAccountId: _this.form.hedgeAccountId,
                openingRule: _this.openingRule,
                closingRule: _this.closingRule,
                deliveryRule: _this.deliveryRule
              })
                .then(() => {
                  _this.$message.success("操作成功");
                  _this.$router.push({ name: "hedgeRule" });
                  resolve();
                })
                .catch(() => {
                  reject();
                });
            });
          }
        });
      });
    },
    // 获取套保账户列表
    getHedgeAccountList() {
      gethedgeaccountlist().then(res => {
        this.accountList = res;
      });
    },
    // 编辑时缓存参数
    cacheParams() {
      if (this.isUpdate) {
        querycompanyhedgeconfig({
          id: this.$route.query.id
        }).then(res => {
          this.updateData = res;
          // 回写数据
          let writeBack = () => {
            // 根据categoryName查找品种详情，获取一二级id
            let category = this.resource.categoryList.find(
              i => i.categoryName === res.categoryName
            );
            this.form.categoryId = [category.categoryType, category.id];
            this.form.hedgeAccountId = res.hedgeAccountId;
            this.openingRule = res.openingRule;
            this.closingRule = res.closingRule;
            this.deliveryRule = res.deliveryRule;
          };
          writeBack();
          // if (this.$route.params.id) {
          //   this.updateData = this.$route.params;
          //   writeBack();
          //   this.$storage.s_set("hedgeStrategy-update", this.$route.params);
          // } else if (this.$storage.s_get("hedgeStrategy-update")) {
          //   let p = this.$storage.s_get("hedgeStrategy-update");
          //   this.updateData = p;
          //   writeBack();
          // } else {
          //   this.$error({
          //     title: "数据错误，请返回列表重新进入"
          //   });
          // }
        });
      }
    },
    // 获取过滤的品种
    getFilterCategorys() {
      let data = this.$route.params;
      // 查询品种id
      let getCategoryID = data => {
        let f = [];
        this.resource.categoryList.forEach(item => {
          if (data.indexOf(item.categoryName) !== -1) {
            f.push(item.id);
          }
        });
        return f;
      };
      if (data.filterCategorys) {
        if (this.isUpdate) {
          // 编辑时，当前编辑的品种不需要过滤
          data.filterCategorys.splice(
            data.filterCategorys.indexOf(data.categoryName),
            1
          );
          this.filterCategorys = getCategoryID(data.filterCategorys);
        } else {
          this.filterCategorys = getCategoryID(data.filterCategorys);
        }
      }
    }
  },
  created() {
    this.getHedgeAccountList();
    this.cacheParams();
    this.getFilterCategorys();
  },
  beforeDestroy() {
    this.$storage.s_remove("hedgeStrategy-filterCategorys");
    // this.$storage.s_remove("hedgeStrategy-update");
  }
};
</script>

<style lang="scss" scoped>
.ant-card {
  margin-bottom: 20px;
}
::v-deep .ant-select-tree-child-tree-open {
  max-height: 400px;
  overflow: auto;
}
.hedgeWarehouse {
  ::v-deep .ant-descriptions-item-label {
    width: 190px;
  }
}
.hedgeDelivery {
  .ant-radio-wrapper {
    white-space: normal;
    margin-bottom: 2em;
  }
}
</style>
